//
//  ForgetPWViewController.m
//  CarUser
//
//  Created by 王森林 on 2019/1/23.
//  Copyright © 2019年 王森林. All rights reserved.
//

#import "ForgetPWViewController.h"
#import "UserRes.h"
@interface ForgetPWViewController ()
{
      dispatch_source_t _timer;
    
}
@property  (nonatomic, strong) UITextField *mobileField;
@property  (nonatomic, strong) UITextField *codeField;
@property  (nonatomic, strong) UITextField *oldPWField;
@property  (nonatomic, strong) UITextField *newPWField;
@property  (nonatomic, strong) UITextField *newCPWField;
@property  (nonatomic, strong) UIButton *codeBtn;
@end

@implementation ForgetPWViewController


- (void)dealloc{
    if (_timer != nil) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"忘记密码";
    [self createUI];
    // Do any additional setup after loading the view.
}

-(void)createUI
{
    UIView *mobileView = [self createViewWithField:self.mobileField showBtn:nil];
    mobileView.frame = CGRectMake(0, 0, BOUNDWIDTH, 50);
    [self.view addSubview:mobileView];
    
    UIView *codeView = [self createViewWithField:self.codeField showBtn:self.codeBtn];
    codeView.frame = CGRectMake(0, 50, BOUNDWIDTH, 50);
    [self.view addSubview:codeView];
    
    UIView *oldPWView = [self createViewWithField:self.oldPWField showBtn:nil];
    oldPWView.frame = CGRectMake(0, 100, BOUNDWIDTH, 50);
    [self.view addSubview:oldPWView];
    
    UIView *newPWView = [self createViewWithField:self.newPWField showBtn:nil];
    newPWView.frame = CGRectMake(0, 150, BOUNDWIDTH, 50);
    [self.view addSubview:newPWView];
    
    UIView *newPWCView = [self createViewWithField:self.newCPWField showBtn:nil];
    newPWCView.frame = CGRectMake(0, 200, BOUNDWIDTH, 50);
    [self.view addSubview:newPWCView];
    
    
    
    UIButton *resetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [resetBtn setBackgroundColor:RGB(254, 218, 60)];
    resetBtn.frame = CGRectMake(15, 280, BOUNDWIDTH - 30, 45);
    resetBtn.layer.cornerRadius = 15;
    resetBtn.layer.masksToBounds = YES;
    resetBtn.titleLabel.font = FONT_SIZE(15);
    [resetBtn setTitleColor:Common_TextColor forState:UIControlStateNormal];
    [resetBtn setTitle:@"重置密码" forState:UIControlStateNormal];
    [resetBtn addTarget:self action:@selector(handleUpdateAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view  addSubview:resetBtn];
    
    
}

- (void)updatePW
{
    

    
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"USERNAME"],
                             @"USERNAME":self.mobileField.text,
                             @"CODE":self.codeField.text,
                             @"NEWPWD":self.newCPWField.text
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_FORGETPW params:params md5Paraname:@"" success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        //        [subscriber sendCompleted];
//        [CommonMethod saveUser:nil];
        [self.navigationController popToRootViewControllerAnimated:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showInfoWithStatus:@"修改成功"];
            //                [SVProgressHUD dismissWithDelay:10];
        });
//        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_Fresh_Userinfo object:nil];
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
}

//更新密码
- (void)handleUpdateAction
{
    
    if ([CommonMethod isBlankString:self.mobileField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码"];
        return ;
    }
    if ([CommonMethod isBlankString:self.codeField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        return ;
    }
    if ([CommonMethod isBlankString:self.oldPWField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入旧密码"];
        return ;
    }
    if ([CommonMethod isBlankString:self.newPWField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入新密码"];
        return ;
    }
    if ([CommonMethod isBlankString:self.newCPWField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入确认新密码"];
        return ;
    }
    
    if (![self.newCPWField.text isEqualToString:self.newPWField.text]) {
        [SVProgressHUD showErrorWithStatus:@"2次密码输入不一样"];
        return ;
    }
    //验证验证码
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"mobile"],
                             @"mobile":self.mobileField.text,
                             @"code":self.codeField.text
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_70 params:params md5Paraname:@"" success:^(id  _Nullable response) {
        [self startTimer];
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        [self updatePW];
        
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
}

//获取验证码
- (void)handleGetCode
{
    
    if ([CommonMethod isBlankString:self.mobileField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码"];
        return ;
    }
    
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"mobile"],
                             @"mobile":self.mobileField.text,
                             @"type":@"1"
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_CreateIdentifyCode params:params md5Paraname:@"" success:^(id  _Nullable response) {
        [self startTimer];
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        //        [subscriber sendCompleted];
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        //        [subscriber sendCompleted];
    }];
}


//倒计时
- (void)startTimer{
    __block int counts = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (counts <= 0) {
                dispatch_source_cancel(self->_timer);
                self.codeBtn.enabled = YES;
                self.codeBtn.titleLabel.text = @"获取验证码";
                [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                self.codeBtn.titleLabel.font = FONT_SIZE(14);
                [self.codeBtn setTitleColor:RGB(50, 50, 50) forState:UIControlStateNormal];
            }else{
                self.codeBtn.enabled = NO;
                self.codeBtn.titleLabel.text = [NSString stringWithFormat:@"%d秒后重新获取",counts];
                [self.codeBtn setTitle:[NSString stringWithFormat:@"%d秒后重新获取",counts] forState:UIControlStateNormal];
                [self.codeBtn setTitleColor:RGB(136, 136, 136) forState:UIControlStateNormal];
                self.codeBtn.titleLabel.font = FONT_SIZE(12);
            }
            counts --;
        });
    });
    dispatch_resume(_timer);
}


-  (UIView *)createViewWithField:(UITextField *)textField showBtn:(UIButton *)btn
{
    UIView *bgView = [UIView new];
    
    if (btn) {
        btn.frame =  CGRectMake(BOUNDWIDTH - 130,10 , 100, 30);
        textField.frame = CGRectMake(15, 0, BOUNDWIDTH - 145, 50);
        [bgView addSubview:textField];
        [bgView addSubview:btn];
    }  else {
        textField.frame = CGRectMake(15, 0, BOUNDWIDTH - 30, 50);
        [bgView addSubview:textField];
    }
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 49.5, BOUNDWIDTH - 30, 0.5)];
    label.backgroundColor = Common_SepeColor;
    [bgView addSubview:label];
    
    return bgView;
    
    
}

- (UITextField *)mobileField
{
    if (!_mobileField) {
        _mobileField  = [[UITextField alloc] init];
        _mobileField.font = FONT_SIZE(15);
        _mobileField.placeholder = @"请输入账号";
    }
    return _mobileField;
}

- (UITextField *)codeField
{
    if (!_codeField) {
        _codeField  = [[UITextField alloc] init];
        _codeField.font = FONT_SIZE(15);
        _codeField.placeholder = @"请输入验证码";
    }
    return _codeField;
}

- (UITextField *)oldPWField
{
    if (!_oldPWField) {
        _oldPWField  = [[UITextField alloc] init];
        _oldPWField.text = @"密码由6-25个字母、数字、符号组成";
        _oldPWField.textColor = [UIColor blackColor];
        _oldPWField.enabled = NO;
        _oldPWField.font = FONT_SIZE(15);
    }
    return _oldPWField;
}
- (UITextField *)newPWField
{
    if (!_newPWField) {
        _newPWField  = [[UITextField alloc] init];
        _newPWField.placeholder = @"请输入新密码";
        _newPWField.font = FONT_SIZE(15);
        _newPWField.secureTextEntry = YES;
    }
    return _newPWField;
}

- (UITextField *)newCPWField
{
    if (!_newCPWField) {
        _newCPWField  = [[UITextField alloc] init];
        _newCPWField.placeholder = @"请确认新密码";
        _newCPWField.font = FONT_SIZE(15);
        _newCPWField.secureTextEntry = YES;
    }
    return _newCPWField;
}

- (UIButton *)codeBtn
{
    if (!_codeBtn) {
        _codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_codeBtn setBackgroundColor:RGB(254, 218, 60)];
        _codeBtn.layer.cornerRadius = 15;
        _codeBtn.layer.masksToBounds = YES;
        _codeBtn.titleLabel.font = FONT_SIZE(14);
        [_codeBtn setTitleColor:RGB(50, 50, 50) forState:UIControlStateNormal];
        [_codeBtn addTarget:self action:@selector(handleGetCode) forControlEvents:UIControlEventTouchUpInside];
        [_codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
    return _codeBtn;
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
